import { Eldisplay, CreateElement } from '../types/element-type'

/**
 * 创建元素
 * @param options
 * @returns
 */
export const createElement = <T, K>(options: CreateElement<T, K>): HTMLElement => {
    const el = document.createElement(options.tagName)

    if (options.attributes) {
        for (const key in options.attributes) {
            el.setAttribute(key, options.attributes[key])
        }
    }

    if (options.data) {
        for (const key in options.data) {
            el.dataset[key] = options.data[key]
        }
    }

    if (options.className) {
        options.className.split(' ').forEach(name => {
            el.classList.add(name)
        })
    }

    if (options.text) {
        el.textContent = options.text
    }

    if (options.childNodes) {
        options.childNodes.forEach((node: HTMLElement) => {
            el.appendChild(node)
        })
    }

    return el
}

/**
 * 移除元素
 * @param el
 */
export const removeElement = (el: HTMLElement): void => {
    if (el.parentNode) el.parentNode.removeChild(el)
}

/**
 * 设置元素状态（显示/隐藏）
 * @param el
 * @param state hide:隐藏 show:显示
 */
export const setElementStatus = (el: HTMLElement, state: 'hide' | 'show') => {
    el.style.display = Eldisplay[state]
}

const a = createElement({ tagName: 'span' })
setElementStatus(a, 'show')

// 调用创建元素并自动推导例子

interface Attributes {
    key: string
}

interface Data2 {
    com: string
}

const O: Attributes = {
    key: '123'
}

const abc = document.createElement('span')

createElement<Attributes, Data2>({
    tagName: 'div',
    attributes: O,
    className: '123',
    childNodes: [abc]
})
